package com.sanchunhui.psc.ui.activity

import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.util.TypedValue
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.ListView
import android.widget.TextView
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.recyclerview.widget.LinearLayoutManager
import com.eightbitlab.rxbus.Bus
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.kennyc.view.MultiStateView
import com.sanchunhui.psc.R
import com.sanchunhui.psc.common.BaseApplication
import com.sanchunhui.psc.data.protocol.*
import com.sanchunhui.psc.event.AddSearchMemberEvent
import com.sanchunhui.psc.event.UpdateSelectMemberCountEvent
import com.sanchunhui.psc.ext.onClick
import com.sanchunhui.psc.ext.startLoading
import com.sanchunhui.psc.injection.component.DaggerProjectTeamComponent
import com.sanchunhui.psc.injection.module.ProjectTeamModule
import com.sanchunhui.psc.presenter.SearchMemberPresenter
import com.sanchunhui.psc.presenter.view.SearchMemberView
import com.sanchunhui.psc.ui.adapter.CompanyDropDownAdapter
import com.sanchunhui.psc.ui.adapter.JobDropDownAdapter
import com.sanchunhui.psc.ui.adapter.SearchMemberAdapter
import com.sanchunhui.ui.activity.BaseMvpActivity
import com.yyydjk.library.DropDownMenu
import kotlinx.android.synthetic.main.activity_search_members.*
import org.jetbrains.anko.find
import org.json.JSONException
import org.json.JSONObject
import kotlin.collections.ArrayList


/**
 * @Author zyx
 * @Date 2021/7/13-12:59
 * @Dscribe
 */
class SearchMemberActivity : BaseMvpActivity<SearchMemberPresenter>(), SearchMemberView, View.OnClickListener {

    private lateinit var mSearchMemberAdapter: SearchMemberAdapter
    private lateinit var companyAdapter: CompanyDropDownAdapter
    private lateinit var jobAdapter: JobDropDownAdapter

    private lateinit var mTeamId : String
    private var teamLeaderName : String = ""
    private var leaderMemberId : String = ""
    private lateinit var intentStr : String

    private lateinit var companyView : ListView
    private lateinit var jobView : ListView
    private lateinit var mDropDownMenu: DropDownMenu
    private val popupViews = java.util.ArrayList<View>()
    private val headers = arrayOf("公司", "工种")

    var mCompanyList = mutableListOf<Company>()
    var mJobList = mutableListOf<Job>()

    var companyId : Int? = null
    var jobId : Int? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_search_members)
        initObserve()
        initView()
        loadCompanyData()
        loadJobData()
    }

    override fun onStart() {
        super.onStart()
        loadData()
    }

    override fun onClick(v: View?) {
        when(v?.id) {
            R.id.mLeftIv -> finish()
            R.id.mSearchTv -> doSearch()
        }
    }

    override fun onBackPressed() {
        super.onBackPressed()
        if (intentStr.isNotEmpty() && intentStr == "1") {
            val intent = Intent()
            intent.putExtra("teamLeaderName", teamLeaderName)
            intent.putExtra("leaderMemberId", leaderMemberId)
            setResult(1, intent)
            finish()
        }

        if (mDropDownMenu.isShowing) {
            mDropDownMenu.closeMenu()
        } else {
            super.onBackPressed()
        }

    }

    fun loadCompanyData() {
        val user = BaseApplication.mUser
        mPresenter.getCompanyList(user.token.toString())
    }

    fun loadJobData() {
        val user = BaseApplication.mUser
        mPresenter.getJobList(user.token.toString())
    }

    /*
        注册监听
     */
    private fun  initObserve() {
        Bus.observe<AddSearchMemberEvent>().subscribe {
            run {
                teamLeaderName = it.name
                leaderMemberId = it.leaderMemberId.toString()
                if (it.name.isEmpty()) {
                    doneBt.setText("完成")
                } else {
                    doneBt.setText("完成(1)")
                }

            }
        }
        Bus.observe<UpdateSelectMemberCountEvent>().subscribe {
            run {
                if (it.count == 0) {
                    doneBt.setText("完成")
                } else {
                    doneBt.setText("完成(${it.count})")
                }
            }
        }

    }

    /*
        初始化视图
     */
    private fun initView() {

        mLeftIv.onClick(this)
        doneBt.onClick(this)
        mSearchTv.onClick(this)

        // RecyclerView适配器
        mSearchMemberAdapter = SearchMemberAdapter(this)
        mSearchMemberRv.layoutManager = LinearLayoutManager(this)
        mSearchMemberRv.adapter = mSearchMemberAdapter

        // 创建公司列表视图
        companyView = ListView(this)
        companyAdapter = CompanyDropDownAdapter(this, mCompanyList)
        companyView.setDividerHeight(0)
        companyView.adapter = companyAdapter

        // 创建工种列表视图
        jobView = ListView(this)
        jobAdapter = JobDropDownAdapter(this, mJobList)
        jobView.setDividerHeight(0)
        jobView.adapter = jobAdapter

        popupViews.add(companyView)
        popupViews.add(jobView)

        //add item click event
        companyView.setOnItemClickListener(AdapterView.OnItemClickListener { parent, view, position, id ->
            companyAdapter.setCheckItem(position)
            mDropDownMenu.setTabText(if (position == 0) headers[0] else mCompanyList[position].name)
            mDropDownMenu.closeMenu()
            companyId = mCompanyList[position].id
            val user = BaseApplication.mUser
            mPresenter.getSearchMember(user.token.toString(),mKeywordEt.text.toString(),companyId,jobId)
        })

        jobView.setOnItemClickListener(AdapterView.OnItemClickListener { parent, view, position, id ->
            jobAdapter.setCheckItem(position)
            mDropDownMenu.setTabText(if (position == 0) headers[1] else mJobList[position].name)
            mDropDownMenu.closeMenu()
            jobId = mJobList[position].id
            val user = BaseApplication.mUser
            mPresenter.getSearchMember(user.token.toString(),mKeywordEt.text.toString(),companyId,jobId)
        })

        val contentView = TextView(this)
        contentView.layoutParams =
            ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT
            )
        contentView.text = ""
        contentView.gravity = Gravity.CENTER
        contentView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 0f)

        //init dropdownview
        mDropDownMenu = find(R.id.dropDownMenu)
        mDropDownMenu!!.setDropDownMenu(headers.toMutableList(), popupViews, contentView)

//        //item点击事件
//        mAdapter.mItemClickListener = object : BaseRecyclerViewAdapter.OnItemClickListener<String> {
//            override fun onItemClick(item: String, position: Int) {
//                enterGoodsList(item)
//            }
//        }
        doneBt.setOnClickListener {
            if (intentStr.isNotEmpty() && intentStr == "1") {
                if (teamLeaderName.isEmpty()) {
                    val toast = Toast.makeText(this, "请选择成员", Toast.LENGTH_SHORT)
                    toast.setGravity(Gravity.CENTER, 0, 0)
                    toast.show()
                } else {
                    val intent = Intent()
                    intent.putExtra("teamLeaderName", teamLeaderName)
                    intent.putExtra("leaderMemberId", leaderMemberId)
                    setResult(1, intent)
                    finish()
                }

            } else if (intentStr.isNotEmpty() && intentStr == "2") {
                val memberIdList: MutableList<Int> = arrayListOf()
                mSearchMemberAdapter.mDatas.filter { it.isSelected }
                    .mapTo(memberIdList) { it.id }
                if (memberIdList.size == 0) {
                    val toast = Toast.makeText(this, "请选择成员", Toast.LENGTH_SHORT)
                    toast.setGravity(Gravity.CENTER, 0, 0)
                    toast.show()
                } else {
                    val user = BaseApplication.mUser
                    mPresenter.addTeamMember(mTeamId.toInt(), user.token.toString(),memberIdList)
                }
            }
        }

        val intent = getIntent()
        intentStr = intent.getStringExtra("intentStr")
        if (intentStr.equals("2")) {
            mTeamId = intent.getStringExtra("teamIdStr")
        }
        mSearchMemberAdapter.setIntentStr(intentStr)
    }

    //搜索
    private fun doSearch() {
        if (mKeywordEt.text.isNullOrEmpty()) {
            val toast = Toast.makeText(this, "请输入需要搜索的关键字", Toast.LENGTH_SHORT)
            toast.setGravity(Gravity.CENTER, 0, 0)
            toast.show()
        } else {
            val inputValue = mKeywordEt.text.toString()
            val user = BaseApplication.mUser
            mPresenter.getSearchMember(user.token.toString(), inputValue, companyId, jobId)
        }
    }

    /*
        从SP中加载数据
     */
    private fun loadData() {

        val user = BaseApplication.mUser
        mSearchMultiStateView.startLoading()
        mPresenter.getSearchMember(user.token.toString().trim(),"",0,0)
    }

    override fun injectComponent() {
        DaggerProjectTeamComponent.builder().activityComponent(mActivityComponent).projectTeamModule(ProjectTeamModule()).build().inject(this)
        mPresenter.mView = this
    }

    @RequiresApi(Build.VERSION_CODES.N)
    override fun onGetComanyListResult(result: ResponseInfo) {
        if (result.code == 0) {
            val json = result.data.toString()
            val map = getMap(json)

            map!!.forEach { s, any ->
                var company = Gson().fromJson(any.toString(), Company::class.java)
                mCompanyList.add(company)
//                println("$s \t $any")
            }
            val firstComany = Company("不限","不限",0)
            mCompanyList.add(0,firstComany)

        } else {
            val toast = Toast.makeText(this, result.message, Toast.LENGTH_SHORT)
            toast.setGravity(Gravity.CENTER, 0, 0)
            toast.show()
        }
    }

    @RequiresApi(Build.VERSION_CODES.N)
    override fun onGetJobListResult(result: ResponseInfo) {
        if (result.code == 0) {
            val json = result.data.toString()
            val map = getMap(json)
            map!!.forEach { s, any ->
                var job = Gson().fromJson(any.toString(), Job::class.java)
                mJobList.add(job)
//                println("$s \t $any")
            }

            val firstJob = Job("不限",0)
            mJobList.add(0,firstJob)

        } else {
            val toast = Toast.makeText(this, result.message, Toast.LENGTH_SHORT)
            toast.setGravity(Gravity.CENTER, 0, 0)
            toast.show()
        }
    }

    override fun onGetSearchMemberResult(result: MutableList<UserInfo>?) {
        if (result != null && result.size > 0) {
            mSearchMemberAdapter.setData(result)
            mSearchMultiStateView.viewState = MultiStateView.ViewState.CONTENT
        } else {
            mSearchMultiStateView.viewState = MultiStateView.ViewState.EMPTY
        }
    }

    override fun onGetAddTeamMemberResult(result: Boolean) {
        val toast = Toast.makeText(this, "添加成功", Toast.LENGTH_SHORT)
        toast.setGravity(Gravity.CENTER, 0, 0)
        toast.show()
        finish()
    }

    override fun onError(text: String) {
        super.onError(text)

    }

    // josn字符串转map
    fun getMap(jsonString: String?): HashMap<String, Any>? {
        val jsonObject: JSONObject
        try {
            jsonObject = JSONObject(jsonString)
            val keyIter: Iterator<String> = jsonObject.keys()
            var key: String
            var value: Any
            var valueMap = HashMap<String, Any>()
            while (keyIter.hasNext()) {
                key = keyIter.next()
                value = jsonObject[key] as Any
                valueMap[key] = value
            }
            return valueMap
        } catch (e: JSONException) {
            e.printStackTrace()
        }
        return null
    }

    /*
      解析数据
  */
    fun parserJson(json: String) {
        val gson = Gson()
        var resultList : ArrayList<UserInfo> = gson.fromJson(json, object : TypeToken<List<UserInfo>>() {}.type)

        if (resultList.isNotEmpty()) {
            mSearchMemberAdapter.setData(resultList)
            mSearchMultiStateView.viewState = MultiStateView.ViewState.CONTENT
        } else {
            mSearchMultiStateView.viewState = MultiStateView.ViewState.EMPTY
        }
    }


}